package com.xcoder.leetcode;

/**
 * https://leetcode-cn.com/problems/maximum-subarray/
 */
public class _53_最大子序和 {

    /**
     * 动态规划
     */
    private static int maxSubArray(int[] nums) {
        int pre = 0, maxSum = nums[0];
        for (int x : nums) {
            pre = Math.max(pre + x, x);
            maxSum = Math.max(maxSum, pre);
        }
        return maxSum;
    }


    /**
     * 分治
     */
    private static int maxSubArray2(int[] nums) {
        return getInfo(nums, 0, nums.length - 1).mSum;
    }

    private static Status getInfo(int[] arr, int l, int r) {
        if (l == r) {
            return new Status(arr[l], arr[l], arr[l], arr[l]);
        }
        int mid = (l + r) >> 1;
        Status lSub = getInfo(arr, l, mid);
        Status rSub = getInfo(arr, mid + 1, r);
        return pushUp(lSub, rSub);
    }

    private static Status pushUp(Status l, Status r) {
        int iSum = l.iSum + r.iSum;
        int lSum = Math.max(l.lSum, l.iSum + r.lSum);
        int rSum = Math.max(r.rSum, r.iSum + l.rSum);
        int mSum = Math.max(Math.max(l.mSum, r.mSum), l.rSum + r.lSum);
        return new Status(lSum, rSum, mSum, iSum);
    }

    private static class Status {
        public int lSum, rSum, mSum, iSum;

        public Status(int lSum, int rSum, int mSum, int iSum) {
            this.lSum = lSum;
            this.rSum = rSum;
            this.mSum = mSum;
            this.iSum = iSum;
        }
    }

}
